<template>
  <el-card>
    <!-- 1.0 显示头部标题（可选） -->
    <template #header>
      <h3>个人中心</h3>
    </template>

    <template>
      <ul>
        <li>
          <span>管理员ID:</span>
          <p>{{ userData.id }}</p>
        </li>
        <li>
          <span>账号:</span>
          <p>{{ userData.account }}</p>
        </li>
        <li>
          <span>用户组:</span>
          <p>{{ userData.userGroup }}</p>
        </li>
        <li>
          <span>创建时间:</span>
          <p>{{ userData.ctime }}</p>
        </li>
        <li>
          <span>管理员头像:</span>
          <p>
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-button size="mini" type="primary" @click="editAva"
              >保存头像</el-button
            >
          </p>
        </li>
      </ul>
    </template>
  </el-card>
</template>

<script>
import local from '@/utils/local.js'
import { editAvatar } from '@/api/users.js'
export default {
  data() {
    return {
      userData: {},
      imageUrl: '',
      uploadUrl: ''
    }
  },
  created() {
    // 取出存储在本地的个人中心的数据
    this.userData = JSON.parse(local.get('users'))
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.uploadUrl = res.imgUrl
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传头像
    async editAva() {
      const { code, msg } = await editAvatar({
        imgUrl: this.uploadUrl
      })

      // console.log(data)
      if (code === 0) {
        this.$message({
          type: 'success',
          message: msg
        })
        location.reload()
      }
    }
  }
}
</script>

<style lang="less" scoped>
li {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #e4e4e4;

  > span {
    width: 120px;
    margin-right: 20px;
  }
}

// less 的穿刺写法
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}

.el-button {
  margin: 10px;
}
</style>
